package portal.controller;

import beans.*;
import engine.BIEngine0_1.AlgorithmOperator;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import portal.engine.JobOperator;
import portal.util.PaserPage;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class ClusterInfrastructureMonitor extends HttpServlet {

    private static final long serialVersionUID = 1L;

    public ClusterInfrastructureMonitor() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String token = "";
        Integer onePageCount = Integer.parseInt(request.getParameter("onePageCount"));
        Integer currentPage = Integer.parseInt(request.getParameter("currentPage"));
        /**
         * 从服务器获取token
         */
        HttpResult tokenResult = JobOperator.getToken(HttpConfig.userName, HttpConfig.passWord);
        if (tokenResult.isResult()) {
            token = tokenResult.getMessage();
        }
        //获取节点资源
        HttpResultList httpResultList = AlgorithmOperator.getJobBasicState(token);
        List<Object> hostList = new ArrayList<>();
        for (int i = 0; i < httpResultList.getDatas().size(); i++) {
            BaseResourceState baseResourceState = (BaseResourceState) httpResultList.getDatas().get(i);
            hostList.add(baseResourceState);
         }

        JSONArray jsonArray = PaserPage.returnCurrentDataList(currentPage,onePageCount, JSONArray.fromObject(hostList));
        for(int i=0;i<jsonArray.size();i++){
            jsonArray.getJSONObject(i).put("totalNumberOfCPU","5");
            jsonArray.getJSONObject(i).put("availableCPUNumber","5");
            jsonArray.getJSONObject(i).put("jobUsedCPUNumber","5");
        }
        JSONObject result = new JSONObject();
        int pageNum = (hostList.size()-1)/onePageCount + 1;
        result.put("message",jsonArray);
        result.put("pageNum",pageNum);
        response.getWriter().write(result.toString());
    }

}
